using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;
using WWB.SitePointPrivateMessages.Core.Infrastructure.Logging;
using WWB.SitePointPrivateMessages.Core.Model.Messages;

namespace WWB.SitePointPrivateMessages.Core.Model.DataImport
{
    public class ExportedMessage
    {
        [XmlElement("datestamp")]
        public string DateStamp { get; set; }
        [XmlElement("title")]
        public string Title { get; set; }
        [XmlElement("fromuser")]
        public string FromUser { get; set; }
        [XmlElement("fromuserid")]
        public int? FromUserId { get; set; }
        [XmlElement("touser")]
        public string ToUser { get; set; }
        [XmlElement("message")]
        public string MessageBody { get; set; }

        public const string DateStampFormat = "yyyy-MM-dd HH:mm";

        public PrivateMessage ConvertToMessage(IList<ForumUser> userList, ILogger outputLog)
        {
            outputLog.LogMessage("Importing message '{0}' sent {1}.", new object[] {Title, DateStamp});
            var pm = new PrivateMessage
                         {
                             DateStamp = DateTime.Parse(DateStamp), 
                             Title = Title, 
                             Body = MessageBody
                         };
            var usr = userList.FirstOrDefault(x => x.Name == FromUser);
            if (usr != null)
            {
                if (usr.Id == ForumUser.UnknownId && FromUserId != null)
                {
                    usr.Id = (int) FromUserId;
                    outputLog.LogMessage("User named '{0}' found and given Id number {1}.",
                                         new object[] {usr.Name, usr.Id});
                }
                outputLog.LogMessage("FromUser mapped to user {0}.", usr);
            }
            else
            {
                usr = new ForumUser()
                          {
                              Id = FromUserId ?? ForumUser.UnknownId,
                              Name = FromUser
                          };
                userList.Add(usr);
                outputLog.LogMessage("FromUser not found. Created user {0}.", usr);
            }
            pm.FromUser = usr;
            pm.ToUsers = createFromUsers(userList, outputLog);
            outputLog.LogMessage("PrivateMessage with fingerprint {0} created.", pm.FingerPrint);
            return pm;
        }

        private IList<ForumUser> createFromUsers(IList<ForumUser> userList, ILogger outputLogger)
        {
            var froms = ToUser.Split(",".ToCharArray());
            var ret = new List<ForumUser>(froms.Count());
            foreach (var un in froms)
            {
                var userName = un.Trim();
                var fu = userList.FirstOrDefault(x => x.Name == userName);
                if (fu != null)
                {
                    ret.Add(fu);
                    outputLogger.LogMessage("Message sent to {0} who was found in the users list.", fu);
                }
                else
                {
                    var newUser = new ForumUser() {Id = ForumUser.UnknownId, Name = userName};
                    userList.Add(newUser);
                    ret.Add(newUser);
                    outputLogger.LogMessage("Message sent to {0} who was not found in the users list.", newUser);
                }
            }
            return ret;
        }
    }
}